package gateway.mgt

import com.amihaiemil.camel.Yaml
import gateway.mgt.api.ApiDefinition
import gateway.mgt.api.ApiGroup
import grails.testing.gorm.DomainUnitTest
import spock.lang.Specification

class ApiDefinitionSpec extends Specification implements DomainUnitTest<ApiDefinition> {

    static ApiGroup apiGroup = new ApiGroup(name: "default")

    static final ValidPropertiesSet = [
            [
                    apiGroup: apiGroup, name: "demo1", description: "demo api 1",
                    request : [path: "/Service-Set-1/sampleApi1"],
                    backend : [uri: "lb://Service-Set-1", path: "/sampleApi1"],
                    result  : [faultContent: "error"]
            ]
    ]

    static final InvalidPropertiesSet = [
            [
                    apiGroup              : apiGroup, name: null, description: "demo api 1",
                    request               : [path: "/Service-Set-1/sampleApi1"],
                    backend               : [uri: "lb://Service-Set-1", path: "/sampleApi1"],
                    expected_error_counter: 1
            ]
    ]


    def setupSpec() {
        apiGroup.save()
    }

    def setup() {
    }

    def cleanup() {
    }

    void "test a valid properties"() {
        given:
        def instance = new ApiDefinition(params)

        when:
        instance.save(flush: true)

        then:
        !instance.hasErrors()

        where:
        params << ValidPropertiesSet
    }

    void "test an invalid properties"() {
        given:
        def instance = new ApiDefinition(params)

        when:
        instance.save(flush: true)

        then:
        instance.hasErrors()

        and:
        instance.errors.allErrors.size() == params.expected_error_counter

        where:
        params << InvalidPropertiesSet
    }

    void "test method 'route(Map)'"() {
        given:
        def instance = ApiDefinition.get(new ApiDefinition(params).save(flush: true).id)

        def groupBuildElements = [routes: Yaml.createYamlSequenceBuilder(), hystrix: Yaml.createYamlMappingBuilder()]

        when:
        instance.route(groupBuildElements)
        def yaml = Yaml.createYamlInput(groupBuildElements.routes.build().toString()).readYamlSequence().yamlMapping(0)

        then:
        yaml.string("id") == params.name
        yaml.string("uri") == params.backend.uri
        yaml.yamlSequence("predicates").string(0).endsWith(params.request.path)
        yaml.yamlSequence("filters").size() == 1

        where:
        params << ValidPropertiesSet
    }
}
